package com.ruoyi.cms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.cms.domain.Menu;
import com.ruoyi.cms.mapper.MenuMapper;
import com.ruoyi.cms.service.MenuService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MenuServiceImpl implements MenuService {
	@Autowired
	private MenuMapper menuMapper;
//	@Autowired
//	private RoleMapper roleMapper;

	@Override
	public TableDataInfo<Menu> queryListByPage(Menu params, PageQuery pageQuery) {
        LambdaQueryWrapper<Menu> lqw = new LambdaQueryWrapper<Menu>();
        Page<Menu> page = menuMapper.selectPage(pageQuery.build(), lqw);
		return TableDataInfo.build(page);
	}

	@Override
	public int add(Menu menu) {
		if(StringUtils.isBlank(menu.getParentId())) {
			menu.setParentId(null);
		}
		return menuMapper.insert(menu);
	}

	@Override
	public Menu queryMenuById(String id) {
		Menu menu = menuMapper.selectVoById(id);
		if(StringUtils.isNotBlank(menu.getParentId()) && !"-1".equals(menu.getParentId())) {
			Menu parent = menuMapper.selectVoById(menu.getParentId());
			menu.setParentMenuName(parent.getMenuName());
		}
		return menu;
	}

	@Override
	public int update(Menu menu) {
		return menuMapper.updateById(menu);
	}

	@Override
	public int delete(String id) {
		return menuMapper.deleteById(id);
	}

	@Override
	public List<Menu> queryAll() {
		return menuMapper.selectList();
	}

	@Override
	public List<Menu> queryListByUserId(String userId) {
        return menuMapper.selectList();
	}

	/**
	 * 根据用户ID递归获取所拥有的菜单权限
	 * @param userId
	 * @param menus
	 * @return
	 */
	private List<Menu> recursionGetMenus(String userId, List<Menu> menus) {
		for(int i = 0;i < menus.size();i++) {
			Menu menu = menus.get(i);
			List<Menu> children = menuMapper.selectListByUserId(userId, menu.getId());
			children = recursionGetMenus(userId, children);
			menu.setChildren(children);
		}
		return menus;
	}

	/**
	 * 递归获取所有菜单权限
	 * @param menus
	 * @return
	 */
	private List<Menu> recursionGetMenus(List<Menu> menus) {
		for(int i = 0;i < menus.size();i++) {
			Menu menu = menus.get(i);
			List<Menu> children = menuMapper.selectListByParentId(menu.getId());
			children = recursionGetMenus(children);
			menu.setChildren(children);
		}
		return menus;
	}
}
